<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <p>
      请问一个 yes/no 的问题
      <input v-model="question">
    </p>
    <p>{{ answer}} </p>
    <img :src="url">
  </div>
  <script type="module">
    import { createApp, ref, watch } from './node_modules/vue/dist/vue.esm-browser.js'

    function debounce(cb, delay) {
      let timer
      return function() {
        if(timer) clearTimeout(timer)
        timer = setTimeout(() => {
          cb.call(this, ...arguments)
        }, delay)
      }
    }
    // 封装监听方法
    function watchMethod() {
      const question = ref('')
      const answer = ref('')
      const url = ref('')
      watch(question, debounce(async (newValue, oldValue) => {
        const response = await fetch('https://www.yesno.wtf/api')
        const data = await response.json()
        answer.value = data.answer
        url.value = data.image
      }, 500))

      return {
        question,
        answer,
        url
      }
    }

    createApp({
      setup() {
        return {
          ...watchMethod()
        }
      }
    }).mount('#app')
  </script>
</body>
</html>